package com.zaofan.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;

import com.zaofan.bean.Carrier;
import com.zaofan.bean.CarrierArea;
import com.zaofan.bean.OpenArea;
import com.zaofan.dao.CarrierDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;
import com.zaofan.utils.WebUtils;

public class CarrierService {

	private CarrierDao carrierDao = new CarrierDao();
	private ExpressService expressService = new ExpressService();
	private OpenAreaService openAreaService = new OpenAreaService();
	private CarrierAreaService carrierAreaService = new CarrierAreaService();

	public void delete(Carrier carrier) {
		carrierDao.del(carrier);
	}

	public void add(Carrier carrier) throws ServiceException {
		if (WebUtils.isEmpty(carrier.getName())) {
			throw new ServiceException("请填写正确的经营商的名称!!");
		}
		if(this.findByName(carrier.getName()) != null){
			throw new ServiceException("该经营商的名称已经在使用!!");
		}
		if (WebUtils.isEmpty(carrier.getPhone())) {
			throw new ServiceException("请填写正确的经营商的联系电话!!");
		}
		if (WebUtils.isEmpty(carrier.getScale())) {
			throw new ServiceException("请填写正确的经营商的规模!!");
		}
		if (WebUtils.isEmpty(carrier.getAddress())) {
			throw new ServiceException("请填写正确的经营商的地址!!");
		}
		if (WebUtils.isEmpty(carrier.getPassword())) {
			carrier.setPassword("123456");
		}
		carrier.setPassword(WebUtils.MD5(carrier.getPassword()));
		carrier.setAddTime(new Date());
		carrier.setAddUser("admin");
		carrierDao.add(carrier);
	}

	public void update(Carrier carrier) throws ServiceException {
		if (WebUtils.isEmpty(carrier.getId())) {
			throw new ServiceException("请填写正确的id!!");
		}
		Carrier target = this.findById(carrier.getId());
		if (target == null) {
			throw new ServiceException("请填写正确的id!!");
		}
		target.setUpdateTime(new Date());
		target.setUpdateUser("admin");
		carrierDao.update(carrier);
	}

	public void updateCarrierInfo(Carrier carrier) throws ServiceException {
		if (WebUtils.isEmpty(carrier.getId())) {
			throw new ServiceException("请填写正确的用户id!!");
		}
		Carrier target = this.findById(carrier.getId());
		if (target == null) {
			throw new ServiceException("请填写正确的用户id!!");
		}

		if (!WebUtils.isEmpty(carrier.getName())) {
			target.setName(carrier.getName());
		}
		if (!WebUtils.isEmpty(carrier.getPhone())) {
			target.setPhone(carrier.getPhone());
		}
		if (!WebUtils.isEmpty(carrier.getScale())) {
			target.setScale(carrier.getScale());
		}
		if (!WebUtils.isEmpty(carrier.getAddress())) {
			target.setAddress(carrier.getAddress());
		}
		carrierDao.update(target);
	}

	public List<Carrier> findAll(Map<String, Object> params) {
		List<Carrier> data = carrierDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return carrierDao.count(params);
	}

	public Carrier findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return carrierDao.findOne(params);
	}

	public void setCarrierState(Carrier carrier) {
		try {
			update(carrier);
			if (carrier.getState() == 1) {
				expressService.setStateByCarrierId(carrier.getId(),
						carrier.getState());
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	public void updateCarrierAreaInfo(Integer id, String areaIds)
			throws ServiceException {
		try {
			Carrier carrier = this.findById(id);
			if (carrier == null) {
				throw new ServiceException("运营商信息有误");
			}
			Connection connection = C3p0DataSourceUtils.getConnection();
			QueryRunner runner = new QueryRunner();
			String sql = "";
			try {
				connection.setAutoCommit(false);
				String ids = carrierAreaService.findByCarrierIdAreaToIds(id);
				CarrierArea carrierArea;
				OpenArea area;
				for (String areaIds_s : ids.split(",")) {
					if (areaIds.contains(areaIds_s)) {
						continue;
					}
					sql = "delete from carrierarea where areaId = " + areaIds_s;
					System.err.println(sql);
					runner.update(connection, sql);
					sql = "update openarea set carrierId = 0 and carrierName = '' where carrierId = "
							+ id;
					System.err.println(sql);
					runner.update(connection, sql);
					sql = "update openbuilder set expressId = 0 , expressName = '' where areaId ="
							+ areaIds_s;
					System.err.println(sql);
					runner.update(connection, sql);
					sql = "delete from expressbuilder where areaId = "
							+ areaIds_s;
					System.err.println(sql);
					runner.update(connection, sql);
				}
				if (areaIds != null && !"".equals(areaIds))
					for (String areaIds_s : areaIds.split(",")) {
						Integer areaId = Integer.valueOf(areaIds_s);
						if (ids.contains(areaIds_s)) {
							continue;
						}
						area = openAreaService.findById(areaId);
						if (area == null) {
							throw new ServiceException("区域信息有误!!!");
						}
						area.setCarrierId(id);
						area.setCarrierName(carrier.getName());
						sql = SqlBuilderUtils.builderUpdateSql(OpenArea.class,
								area);
						System.err.println(sql);
						runner.update(connection, sql);
						sql = "delete from expressbuilder where areaId = "
								+ area.getId();
						System.err.println(sql);
						runner.update(connection, sql);
						sql = "update openbuilder set expressId = 0 , expressName = '' where areaId = "
								+ area.getId();
						System.err.println(sql);
						runner.update(connection, sql);
						sql = "delete from carrierarea where areaId = "
								+ areaId;
						System.err.println(sql);
						runner.update(connection, sql);
						carrierArea = new CarrierArea();
						carrierArea.setCarrierId(carrier.getId());
						carrierArea.setAreaId(areaId);
						sql = SqlBuilderUtils.builderInsertSql(
								CarrierArea.class, carrierArea);
						System.err.println(sql);
						runner.update(connection, sql);
					}
				connection.commit();
			} catch (ServiceException e) {
				e.printStackTrace();
				throw e;
			} catch (Exception e) {
				connection.rollback();
				e.printStackTrace();
				throw e;
			} finally {
				connection.close();
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("操作信息有误!!");
		}
	}

	public Carrier login(Carrier carrier) throws ServiceException {
		if (WebUtils.isEmpty(carrier.getName())) {
			throw new ServiceException("请输入账户!!!");
		}
		if (WebUtils.isEmpty(carrier.getPassword())) {
			throw new ServiceException("请输入账户密码!!!");
		}
		Carrier target = this.findByName(carrier.getName());
		if (target == null) {
			throw new ServiceException("请输入正确的账户!!!");
		}
		if (!target.getPassword().equals(WebUtils.MD5(carrier.getPassword()))) {
			throw new ServiceException("请输入正确的账户密码!!!");
		}
		return target;
	}

	private Carrier findByName(String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		return carrierDao.findOne(params);
	}

	public void updatePass(Integer id, String oldPass, String newPass) throws ServiceException {
		Carrier carrier = this.findById(id);
		if (carrier == null) {
			throw new ServiceException("请输入正确的账户!!!");
		}
		if (WebUtils.isEmpty(oldPass)) {
			throw new ServiceException("请输入旧密码!!!");
		}
		if (WebUtils.isEmpty(newPass)) {
			throw new ServiceException("请输入新密码!!!");
		}
		if (!carrier.getPassword().equals(WebUtils.MD5(oldPass))) {
			throw new ServiceException("请输入正确的旧密码!!!");
		}
		carrier.setPassword(WebUtils.MD5(newPass));
		update(carrier);
	}

}
